import { baseUrl } from '@/js/config/index.js'
// 公用的上传方法
export function uploadFunc(file_lists) {
	console.log(file_lists)
	return new Promise((resolve, reject) => {
		if (!file_lists.length) {
			resolve(file_lists)
			return
		}

		const ulpad = (item, index) => {
			item.status = 'uploading'
			item.message = '上传中'
			uni.uploadFile({
				url: baseUrl + '/race/common/upload',
				filePath: item.url,
				name: 'file',
				formData: {},
				header: { 'Content-Type': 'multipart/form-data' },
				success: (uploadFileRes) => {
					let res = JSON.parse(uploadFileRes.data.replace('\uFEFF', ''))
					console.log(res, 'upload--------');

					if (res.code !== 200) {
						item.status = 'error'
						reject('图片上传失败！')
						return
					}
					item.status = 'success'
					item.message = '上传完成'
					item.url = res.data
					// 全部上传完后提交
					if (index === file_lists.length - 1) {
						resolve(file_lists)
					}
				},
				fail: err => {
					reject('图片上传失败！')
					item.status = 'ready'
					item.message = ''
					uni.showToast({ title: '网络错误' })
				}
			})
		}

		for (let i = 0; i < file_lists.length; i++) {
			if (file_lists[i].status === 'uploading' || file_lists[i].status === 'success') {
				if (file_lists[i].status === 'success' && i === file_lists.length - 1) {
					resolve(file_lists)
				}
				continue
			}
			ulpad(file_lists[i], i)
		}
	})
}